<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>添加授权地区</title>
  <link rel="stylesheet" href="__PUBLIC__/node_modules/bootstrap/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="__PUBLIC__/style/base.css">
  <link rel="stylesheet" href="__PUBLIC__/style/add_local.css">
  <script src="https://cdn.jsdelivr.net/npm/babel-polyfill/dist/polyfill.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/jquery"></script>
  <script src="__PUBLIC__/node_modules/cxselect/js/jquery.cxselect.min.js"></script>
</head>
<body>
  <div style="display:none;">
      <input type="hidden" name='获取地区占用列表' id='ifHasDiqu' value="{:U('Index/ajax_gb_area')}">
  </div>
  <div class="form_box">
    <!-- 获取密码 -->
    <input type="hidden" value="{:U('Home/index/sms')}" id="ajax_get_pass">
    <!-- 验证密码 -->
    <input type="hidden" value="{:U('Index/chack_phone')}" id="ajax_auth_pass">
    <!-- 验证手机号是否重复 -->
    <input type="hidden" name="验证手机是否重复" id='re_ck_phone' value="{:U('Home/index/re_ck_phone')}">

    <form autocomplete="off" action="{:U(chengshi)}" method="POST" id='add_post' >
      <input type="hidden" name='u_type' id='hiddenType' value="1">
      <div id="diqu">
        <select name="u_pro_id" id = 'pro' class="province" data-value="广东省" required>
			<foreach name="region" item="v">
				<option value="{$v.id}">{$v.region_name}</option>
			</foreach>
		</select>
        <select name="u_city_id" id="city" class="city" data-value="深圳市" required>
		</select>
        <select style="display:none;" name="u_area_id" id="area" class="area" data-value="龙岗区">
		</select>
      </div>
      <div class="shouquan_name">
        <input type="text" name="u_name" id="shouquan_name" placeholder="授权人姓名" required>
      </div>
      <div class="shouquan_phone">
        <input type="tel" name="u_phone" id="shouquan_phone" placeholder="授权人手机号" required pattern="^(0|86|17951)?(13[0-9]|15[012356789]|17[0678]|18[0-9]|14[57])[0-9]{8}" onkeyup="value=value.replace(/[^\d]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))">
      </div>
      <div class="shouquan_mail">
        <input type="email" name="u_email" id="shouquan_mail" placeholder="授权人邮箱" required>
      </div>
      <div class="shouquan_pass">
        <input type="text" name="u_pass" id="shouquan_pass" placeholder="随机密码" readonly required>
        <br>
        <input type="button" value="密码" id="send_auth_pass">
      </div>
      <input type="submit" value="确定授权" id='add_post_button'>
    </form>
  </div>
 <script>
   $('#pro').change(function(){
        $.ajax({
            type:"post",
            url:"{:U('Index/chengshi')}",
            data:'pro_id='+$('#pro').val(),
            dataType:"json",
            success:function(data){
              $('#city').html(data);
              $('#city').val(null);
              $.each(window._initLocationList.data, (index, item) => {
                if($(`#city option[value='${item.id}']`).length > 0) {
                  // console.log($(`#city option[value='${item.id}']`))
                  $(`#city option[value='${item.id}']`).remove()
                }
              })
              if ($(`#city option`).length === 0) {
                alert('请选择其他省份，该省份所有市区均拥有管理账号')
                $('#pro').val(null)
                $('#pro').change()
              }
            }
        });
    });
	$('#city').change(function(){
    $.ajax({
        type:"post",
        url:"{:U('Index/chengshi')}",
        data:'pro_id='+$('#city').val(),
        dataType:"json",
        success:function(data){
          console.log(data)
          $('#area').html(data);
          $.each(window._initLocationList.data, (index, item) => {
            if($(`#area option[value='${item.id}']`).length > 0) {
              // console.log($(`#area option[value='${item.id}']`))
              $(`#area option[value='${item.id}']`).remove()
            }
          })
        }
      });
  });

  function countDown (sec, ele, fn) {
    // console.log(sec)
    // console.log(ele)
    // console.log(fn)
    if ( typeof sec === 'number' && sec === 0) {
      fn()
    } else if (typeof sec === 'number' && sec > 0) {
      // 需要修改倒数的元素
      $(`#${ele}`).val(`${sec--}秒`)
      return ((sec, ele, fn) => {
        setTimeout(()=>{
          countDown(sec, ele, fn)
        }, 1000)
      })(sec, ele, fn)
    } else {
      ;
    }
  }
  // gen一个随机数值串出来
  function genRandCode (leng) {
    if( String(typeof leng).toLocaleLowerCase() === 'number') return Math.random().toFixed(leng).toString().replace(/\d\./, '')
    else {
      $('#getCode').one({'click': sendCode}, {id: 'getCode', urlID: 'url_getCode', phoneID: 'web_phone'})
      throw new Error(`收到类型不为数值的参数：${leng} | ${String(typeof leng).toLocaleLowerCase()}。无法产生指定长度随机数`)
    }
  }
  const send_code = genRandCode(8)
  function send_pass() {
      let url = $('#ajax_get_pass').val()
      let phone = $('#shouquan_phone').val()
      if (phone === '') {
        $('#send_auth_pass').off('click')
        $('#send_auth_pass').one('click', send_pass)
        alert('请先填写手机号');
      } else {
        $('#send_auth_pass').css('pointer-events','none')
        countDown(60, 'send_auth_pass', function(){
          $('#send_auth_pass').val('密码')
          $('#send_auth_pass').css('pointer-events','unset')
          $('#send_auth_pass').off('click')
          $('#send_auth_pass').one('click', send_pass)
        })

        $.ajax({
          url: url,
          // async: false,
          data: {mobile: phone, send_code: send_code},
          method: 'post'
        }).done((data, code)=> {

          if(data.send_code === `${send_code}` && Number(data.code) === 2) {
            $('#send_auth_pass').remove()
            $('#shouquan_phone').attr('readonly', true)
            $('#shouquan_pass').val(data.send_code)
            $('#add_post_button').off('click')

            $('#add_post_button').on('click', function (event) {
              event.preventDefault();
              $('input:required').each((index, item)=>{
                if($(item).val() === '') {
                  alert('未填写完毕相关表单')
                  throw new Error('未填写完毕相关表单')
                }
              })
              $('select:required').each((index, item)=>{
                if($(item).val() === '') {
                  alert('未填写完毕相关表单')
                  throw new Error('未填写完毕相关表单')
                }
              })
              var formData = $('#add_post').serializeArray()
              var url = "{:U(user_add)}";
              $.ajax({
                type: 'POST',
                url: url,
                data: formData,
                timeout: 30000,
                success:function(data){
                  console.log(data);
                  if(data == 'ok'){
                    window.parent.location.reload();
                    var index=$(window.parent.document).find('.layui-layer-shade').eq(0).attr('times');
                    parent.layer.close(index); //执行关闭
                  }
                }
              })
              return false
            })
          } else {
            $('#send_auth_pass').off('click')
            $('#send_auth_pass').one('click', send_pass)
            window.alert(`网络错误，请重试。服务器提示：${data.msg}`)
          }
        })

      }

  }

  $(document).ready(function() {
    $('#add_post_button').on('click', (event)=>{
      event.preventDefault();
      alert('请先获取密码！')
      return false
    })

    let getSingleInput = (function (value) {
      var input
      return function(){
        if (!input) {
          var input = document.createElement('input')
          $(input).attr('type', 'hidden')
          $(input).attr('name', 'id')
          $(input).attr('value', value)
          $(input).attr('id', 'hiddenID')
        }
        return input
      }.bind(value)
    })()
    $(`#shouquan_phone`).on('change', (evt) => {
      $('#send_auth_pass').off('click')
      $('#send_auth_pass').val('填写正确手机号')
      $('#shouquan_pass').val(null)
      const value = $(`#shouquan_phone`).val()
      const reg = new RegExp(`${$(`#shouquan_phone`).attr('pattern')}`)
      if(`${value.length}` === '11' && reg.test(value)) {
        // 验证手机号码是否重复
        const checkURL = String($('#re_ck_phone').val())
        const ajaxData = {
          phone: value
        }
        $.ajax(checkURL, {
          method: 'post',
          data: ajaxData,
          beforeSend: () => {
            $('#shouquan_phone').attr('readonly', true)
            $('#send_auth_pass').val('正在验证手机号')
          }
        }).fail((err) => {
          $('#shouquan_phone').attr('readonly', false)
          $('#send_auth_pass').val('验证失败')
        }).done((res) => {
          $('#shouquan_phone').attr('readonly', false)
          if (res.code && String(res.code) === '1') {
            $('#send_auth_pass').val('手机号可用')
            $('#send_auth_pass').one('click', send_pass)
            setTimeout(() => {
              $('#send_auth_pass').val('获取密码')
            }, 1000)
          } else if (res.code && String(res.code) === '2') {
            $('#send_auth_pass').val('手机号已注册')
          } else {
            $('#send_auth_pass').val('验证失败')
            console.log(`验证手机时服务器返回：${res}`)
          }
        })
      }
    })
    $('#send_auth_pass').one('click', send_pass)
  })
  $(document).ready(() => {
      $('#pro').val(null)
      const ajaxURL = `${$('#ifHasDiqu').val()}`
      $.ajax(ajaxURL, {
          type: 'get'
      }).fail((err) => {
          alert('获取占用地区列表失败！尝试重新加载页面')
          setTimeout(() => {
              // location.reload(true)
          }, 1000)
      }).done((res) => {
          try {
              window._initLocationList = res
          } catch (err) {
              alert('获取占用地区列表失败！尝试重新加载页面')
              setTimeout(() => {
                  // location.reload(true)
              }, 1000)
              throw err
          }
      })
  })
</script>
</body>
</html>